package com.myredis.e97.service.impl;

import com.myredis.e97.entity.User;
import com.myredis.e97.mapper.UserMapper;
import com.myredis.e97.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
@CacheConfig(cacheNames = "user")
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    @CachePut(key = "'user-id-'+ #user.id" ,unless = "#result==null" )
    public int addUser(User user) {
        System.out.println("写入缓存");
        return userMapper.addUser(user);
    }

    @Override
    @CacheEvict(key = "'user-id-'+#p0")//根据key清除缓存，一般该注解标注在修改和删除方法上
    // #p0 下面方法的第一个形参，以此类推
    public int deleteUser(int id) {
        return userMapper.deleteUser(id);
    }

    @Override
    @CacheEvict(key = "'user-id-'+#user.id")//根据key清除缓存，一般该注解标注在修改和删除方法上
    public int updateUser(User user) {
        System.out.println("更新数据并清除之前的缓存");
        return userMapper.updateUser(user);
    }

    @Override
    @Cacheable(cacheNames = "userList",unless = "#result==null") // 标志读取缓存操作，如果缓存不存在，则调用目标方法，并将结果放入缓存
    public List<User> selectUser() {
        System.out.println("缓存不存在，执行方法");
        return userMapper.selectUser();
    }

    @Override
    @Cacheable(key = "'user-id-'+#p0"  ,unless = "#result==null" )
    public User selectUserById(int id) {
        System.out.println("缓存不存在，执行方法");
        return userMapper.selectUserById(id);
    }

    @Override
    public int countUser() {
        return userMapper.countUser();
    }
}